<template>
	<a-card :bordered="false">
		<a-form ref="searchFormRef" name="advanced_search" :model="searchFormState" class="ant-advanced-search-form">
			<a-row :gutter="24">
				<a-col :span="6">
					<a-form-item label="发生时间" name="createTime">
						<a-range-picker v-model:value="searchFormState.createTime" value-format="YYYY-MM-DD" format="YYYY-MM-DD" />
					</a-form-item>
				</a-col>
				<a-col :span="18">
					<a-button type="default" @click="setDate('0')">今日</a-button>
					<a-button style="margin: 0 1px" @click="setDate('1')">昨日</a-button>
					<a-button style="margin: 0 1px" @click="setDate('2')">本周</a-button>
					<a-button style="margin: 0 1px" @click="setDate('3')">上周</a-button>
					<a-button style="margin: 0 1px" @click="setDate('4')">本月</a-button>
					<a-button style="margin: 0 1px" @click="setDate('5')">上月</a-button>
				</a-col>
			</a-row>
			<a-row :gutter="24">
<!--				<a-col :span="6">-->
<!--					<a-form-item label="商品库查找" name="streamProductionId">-->
<!--						<a-input v-model:value="searchFormState.productionSearchKey" placeholder="请输入条码/名称/拼音码"/>-->
<!--					</a-form-item>-->
<!--				</a-col>-->
				<a-col :span="4">
					<a-form-item label="商品关键字查找" name="searchKey">
						<a-input v-model:value="searchFormState.searchKey" placeholder="请输入条码/名称"/>
					</a-form-item>
				</a-col>
				<a-col :span="5" >
					<a-form-item label="门店（仓库）" name="streamStoreId">
						<a-tree-select
							v-model:value="searchFormState.streamStoreId"
							class="xn-wd"
							:dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
							placeholder="请选择门店（仓库）"
							allow-clear
							tree-default-expand-all
							:tree-data="storeTreeData"
							:tree-default-expanded-keys="storeTreeDefaultExpandedKeys"
							:field-names="{
										children: 'children',
										label: 'name',
										value: 'id'
									}"
						></a-tree-select>
					</a-form-item>
				</a-col>
				<a-col :span="4" >
					<a-form-item label="业务类型" name="streamBusinessType">
						<a-select v-model:value="searchFormState.streamBusinessType" placeholder="请选择业务类型"
								  :options="streamBusinessTypeOptions"/>
					</a-form-item>
				</a-col>
				<a-col :span="5" >
					<a-form-item label="业务对象" name="streamObjectId">
						<xn-page-select
							ref="xnstreamObjectIdPageSelectRef"
							v-model:value="searchFormState.streamObjectId"
							placeholder="请选择业务对象"
							allow-clear
							show-search
							:page-function="streamObjectIdSelector"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="4">
					<a-checkbox v-model:checked="searchFormState.isHavingByProduction" @change="changeIsTotal">汇总</a-checkbox>
					<a-button type="primary" @click="tableRef.refresh()">查询</a-button>
					<a-button style="margin: 0 8px" @click="reset">重置</a-button>
				</a-col>

			</a-row>
			<a-row :gutter="24" v-show="searchFormState.isHavingByProduction">
				<a-col :span="2" >
					汇总选项：
				</a-col>
				<a-col :span="2" >
					<a-checkbox v-model:checked="searchFormState.isHavingByStore" @change="changeTotalOption('isHavingByStore')">按门店汇总</a-checkbox>
				</a-col>
				<a-col :span="2" >
					<a-checkbox v-model:checked="searchFormState.isHavingByStorage" @change="changeTotalOption('isHavingByStorage')">按仓库汇总</a-checkbox>
				</a-col>
				<a-col :span="2" >
					<a-checkbox v-model:checked="searchFormState.isHavingByStoreLocation" @change="changeTotalOption('isHavingByStoreLocation')">按库位汇总</a-checkbox>
				</a-col>
				<a-col :span="2" >
					<a-checkbox v-model:checked="searchFormState.isHavingByProductionBatch" @change="changeTotalOption('isHavingByProductionBatch')">按批次汇总</a-checkbox>
				</a-col>
				<a-col :span="3">
					<a-checkbox v-model:checked="searchFormState.isHavingByDateManufacture" @change="changeTotalOption('isHavingByDateManufacture')">按生产日期汇总</a-checkbox>
				</a-col>
				<a-col :span="3" >
					<a-checkbox v-model:checked="searchFormState.isHavingBySupplier" @change="changeTotalOption('isHavingBySupplier')">按业务对象汇总</a-checkbox>
				</a-col>
				<a-col :span="3" >
					<a-checkbox v-model:checked="searchFormState.isHavingByBusinessType" @change="changeTotalOption('isHavingByBusinessType')">按业务类型汇总</a-checkbox>
				</a-col>
			</a-row>
		</a-form>
		<s-table
			ref="tableRef"
			:columns="columns"
			:data="loadData"
			:alert="options.alert.show"
			bordered
			:row-key="(record) => record.id"
			:tool-config="toolConfig"
			:row-selection="options.rowSelection"
		>
			<template #operator class="table-operator">
				<a-space>
					<a-button @click="exportBatchStream" v-if="hasPerm('supplierWarehouseStoresStreamExport')">
						<template #icon>
							<export-outlined/>
						</template>
						批量导出
					</a-button>
				</a-space>

			</template>
			<template #bodyCell="{ column, record }">
				<template v-if="column.dataIndex === 'streamBusinessType'">
					{{ $TOOL.dictTypeData('BUSSINESS_TYPE', record.streamBusinessType) }}
				</template>
				<template v-if="column.dataIndex === 'streamDateManufacture'">
					{{ $TOOL.parseTime(record.streamDateManufacture, '{y}-{m}-{d}') }}
				</template>
				<template v-if="column.dataIndex === 'action'">
					<a-space>
						<a @click="formRef.onOpen(record)" v-if="hasPerm('supplierWarehouseStoresStreamEdit')">编辑</a>
						<a-divider type="vertical"
								   v-if="hasPerm(['supplierWarehouseStoresStreamEdit', 'supplierWarehouseStoresStreamDelete'], 'and')"/>
						<a-popconfirm title="确定要删除吗？" @confirm="deleteSupplierStoresStream(record)">
							<a-button type="link" danger size="small"
									  v-if="hasPerm('supplierWarehouseStoresStreamDelete')">删除
							</a-button>
						</a-popconfirm>
					</a-space>
				</template>
			</template>
		</s-table>
	</a-card>
	<Form ref="formRef" @successful="tableRef.refresh()"/>
</template>

<script setup name="supplierWarehouseStoresstream">
import tool from '@/utils/tool'
import {cloneDeep} from 'lodash-es'
import Form from './form.vue'
import supplierStoresStreamApi from '@/api/supplier/warehouse/supplierStoresStreamApi'
import supplierProductionsApi from "@/api/supplier/base/supplierProductionsApi";
import supplierStoresApi from "@/api/supplier/base/supplierStoresApi";
import supplierSuppliersApi from "@/api/supplier/purchase/supplierSuppliersApi";
import downloadUtil from "@/utils/downloadUtil";
import {message} from "ant-design-vue";
import supplierObjectsApi from "@/api/supplier/custom/supplierObjectsApi";

const searchFormState = ref({})
const searchFormRef = ref()
const tableRef = ref()
const formRef = ref()
const cardLoading = ref(true)
const storeTreeData = ref([])
const storeTreeDefaultExpandedKeys = ref([])
const toolConfig = {refresh: true, height: true, columnSetting: true, striped: false}

const columns = ref([
	{
		title: '发生时间',
		dataIndex: 'createTime',
		sorter: true
	},

	{
		title: '商品编码',
		dataIndex: 'streamProductionCode',
		sorter: true,
	},
	{
		title: '商品条码',
		dataIndex: 'streamProductionBarcode'
	},
	{
		title: '商品库名称',
		dataIndex: 'streamProductionIdName',
	},
	{
		title: '商品名称',
		dataIndex: 'streamProductionName',
		checked:false,
	},
	{
		title: '商品规格',
		dataIndex: 'streamProductionSpec'
	},
	{
		title: '商品单位',
		dataIndex: 'streamProductionUnit'
	},
	{
		title: '门店ID',
		dataIndex: 'streamStoreIdName'
	},
	{
		title: '仓库ID',
		dataIndex: 'streamStorageIdName'
	},
	{
		title: '库位',
		dataIndex: 'streamStoreLocationName'
	},
	{
		title: '批次',
		dataIndex: 'streamProductionBatch'
	},
	{
		title: '生产日期',
		dataIndex: 'streamDateManufacture'
	},
	{
		title: '入库数量',
		dataIndex: 'streamInNumber'
	},
	{
		title: '出库数量',
		dataIndex: 'streamOutNumber'
	},
	{
		title: '业务类型',
		dataIndex: 'streamBusinessTypeName'
	},
	{
		title: '业务单号',
		dataIndex: 'streamBusinessIdName'
	},
	{
		title: '实时库存',
		dataIndex: 'streamProductionStock'
	},
	{
		title: '业务对象',
		dataIndex: 'streamObjectIdName'
	},
	{
		title: '备注',
		dataIndex: 'remark'
	}
])
// 操作栏通过权限判断是否显示
if (hasPerm(['supplierWarehouseStoresStreamEdit', 'supplierWarehouseStoresStreamDelete'])) {
	columns.push({
		title: '操作',
		dataIndex: 'action',
		align: 'center',
		width: 150
	})
}
const selectedRowKeys = ref([])
// 列表选择配置
const options = {
	// columns数字类型字段加入 needTotal: true 可以勾选自动算账
	alert: {
		show: false,
		clear: () => {
			selectedRowKeys.value = ref([])
		}
	},
	rowSelection: {
		onChange: (selectedRowKey, selectedRows) => {
			selectedRowKeys.value = selectedRowKey
		}
	}
}
//汇总或明细
const changeIsTotal = () => {
	const newColumns = cloneDeep(columns.value)
	searchFormState.value.isHavingByStore = false
	searchFormState.value.isHavingByStorage = false
	searchFormState.value.isHavingByStoreLocation = false
	searchFormState.value.isHavingByProductionBatch = false
	searchFormState.value.isHavingByDateManufacture = false
	searchFormState.value.isHavingBySupplier = false
	searchFormState.value.isHavingByBusinessType = false

	newColumns.forEach(column => {
		if(column.dataIndex === 'streamStoreIdName' || column.dataIndex === 'streamStorageIdName' || column.dataIndex === 'streamStoreLocationName' || column.dataIndex === 'streamProductionBatch' || column.dataIndex === 'streamDateManufacture'
		 || column.dataIndex === 'streamBusinessTypeName' || column.dataIndex === 'streamObjectIdName' || column.dataIndex === 'streamBusinessIdName' || column.dataIndex === 'streamProductionStock' || column.dataIndex === 'remark' || column.dataIndex === 'createTime'){
			column.checked = !searchFormState.value.isHavingByProduction
		}
	})
	columns.value = newColumns
	tableRef.value.refresh()
}
//更改汇总选项
const changeTotalOption = (options) => {
	const newColumns = cloneDeep(columns.value)
	newColumns.forEach(column => {
		if(options === 'isHavingByStore' && column.dataIndex === 'streamStoreIdName'){
			column.checked = searchFormState.value.isHavingByStore
		}
		if(options === 'isHavingByStorage' && column.dataIndex === 'streamStorageIdName'){
			column.checked = searchFormState.value.isHavingByStorage
		}
		if(options === 'isHavingByStoreLocation' && column.dataIndex === 'streamStoreLocationName'){
			column.checked = searchFormState.value.isHavingByStoreLocation
		}
		if(options === 'isHavingByProductionBatch' && column.dataIndex === 'streamProductionBatch'){
			column.checked = searchFormState.value.isHavingByProductionBatch
		}
		if(options === 'isHavingByDateManufacture' && column.dataIndex === 'streamDateManufacture'){
			column.checked = searchFormState.value.isHavingByDateManufacture
		}
		if(options === 'isHavingBySupplier' && column.dataIndex === 'streamObjectIdName'){
			column.checked = searchFormState.value.isHavingBySupplier
		}
		if(options === 'isHavingByBusinessType' && column.dataIndex === 'streamBusinessTypeName'){
			column.checked = searchFormState.value.isHavingByBusinessType
		}
	})
	columns.value = newColumns
	tableRef.value.refresh()
}
const loadData = (parameter) => {
	const searchFormParam = cloneDeep(searchFormState.value)
	if (searchFormParam.createTime){
		searchFormParam.startCreateTime = searchFormParam.createTime[0]
		searchFormParam.endCreateTime = searchFormParam.createTime[1]
		delete searchFormParam.createTime
		return supplierStoresStreamApi.supplierStoresStreamPage(Object.assign(parameter, searchFormParam)).then((data) => {
			return data
		})
	}else{
		if (searchFormParam.createTime ===null){
			message.warn("请确定时间范围")
		}
		return Promise.resolve(null)
	}
}
// 批量导出
const exportBatchStream = () => {
	if (selectedRowKeys.value.length > 0 && !searchFormState.value.isHavingByProduction) {//只有当非汇总模式下才可导出选中的行
		const params = {
			startCreateTime: searchFormState.value.createTime[0],
			endCreateTime: searchFormState.value.createTime[1],
			isHavingByProduction:searchFormState.value.isHavingByProduction,
			ids: selectedRowKeys.value
				.map((m) => {
					return m
				})
				.join()
		}
		supplierStoresStreamApi.supplierStoresStreamExport(params).then((res)=>{
			downloadUtil.resultDownload(res)
			tableRef.value.clearSelected()
		})
		return
	}
	const searchFormParam = cloneDeep(searchFormState.value)
	if (searchFormParam.createTime !==null ) {
		searchFormParam.startCreateTime = searchFormParam.createTime[0]
		searchFormParam.endCreateTime = searchFormParam.createTime[1]
		delete searchFormParam.createTime
		supplierStoresStreamApi.supplierStoresStreamExport(searchFormParam).then((res)=>{
			downloadUtil.resultDownload(res)
			tableRef.value.clearSelected()
		})
	}else{
		message.warn("请确定时间范围")
	}
}
nextTick(()=>{
	setDate('0')
	tableRef.value.refresh()
})
// 重置
const reset = () => {
	searchFormRef.value.resetFields()
	setDate('0')
	tableRef.value.refresh(true)
}
// 删除
const deleteSupplierStoresStream = (record) => {
	let params = [
		{
			id: record.id
		}
	]
	supplierStoresStreamApi.supplierStoresStreamDelete(params).then(() => {
		tableRef.value.refresh(true)
	})
}
// 批量删除
const deleteBatchSupplierStoresStream = (params) => {
	supplierStoresStreamApi.supplierStoresStreamDelete(params).then(() => {
		tableRef.value.clearRefreshSelected()
	})
}

const streamBusinessTypeOptions = tool.dictList('SUPPLIER_BUSINESS_TYPE')
const xnstreamObjectIdPageSelectRef = ref();
const streamObjectIdSelector = (param) => {
	return supplierObjectsApi.supplierObjectsPage(Object.assign(param, {objectType:"0"})).then((data) => {
		if (data.records){
			data.records = data.records.map((item) => {
				return {
					name: item.objectName,
					id: item.id,
				};
			});
		}
		return Promise.resolve(data)
	})
}
nextTick(() => {
	xnstreamObjectIdPageSelectRef.value.onPage({current: 1});
});
nextTick(() => {
	supplierStoresApi.supplierStoresTree().then((res) => {
		if (res !== null) {
			cardLoading.value = false
			storeTreeData.value = [
				{
					id: '',
					parentId: '0',
					name: '全部门店',
					children: res
				}
			]
			// 默认展开2级
			storeTreeData.value.forEach((item) => {
				// 因为0的顶级
				if (item.parentId === '0') {
					storeTreeDefaultExpandedKeys.value.push(item.id)
					// 取到下级ID
					if (item.children) {
						item.children.forEach((items) => {
							storeTreeDefaultExpandedKeys.value.push(items.id)
						})
					}
				}
			})
		}
	}).finally(() => {
		cardLoading.value = false
	})
})
const setDate = (index) => {
	switch (index) {
		case '0':
			var dateArray = []
			dateArray[0] = tool.parseTime(new Date(), '{y}-{m}-{d}')
			dateArray[1] = tool.parseTime(new Date(), '{y}-{m}-{d}')
			searchFormState.value.createTime = dateArray
			break

		case '1':
			var dateArray = []
			dateArray[0] = tool.parseTime(new Date(Date.now() - 24 * 60 * 60 * 1000), '{y}-{m}-{d}')
			dateArray[1] = tool.parseTime(new Date(Date.now() - 24 * 60 * 60 * 1000), '{y}-{m}-{d}')
			searchFormState.value.createTime = dateArray
			break
		case '2':
			var dateArray = []
			dateArray[0] = tool.parseTime(
				new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() - new Date().getDay() + 1),
				'{y}-{m}-{d}'
			)
			dateArray[1] = tool.parseTime(
				new Date(
					new Date().getFullYear(),
					new Date().getMonth(),
					new Date(
						new Date().getFullYear(),
						new Date().getMonth(),
						new Date().getDate() - new Date().getDay()
					).getDate() + 7
				),
				'{y}-{m}-{d}'
			)
			searchFormState.value.createTime = dateArray
			break
		case '3':
			var dateArray = []
			dateArray[0] = tool.parseTime(
				new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() - new Date().getDay() - 6),
				'{y}-{m}-{d}'
			)
			dateArray[1] = tool.parseTime(
				new Date(
					new Date().getFullYear(),
					new Date().getMonth(),
					new Date(
						new Date().getFullYear(),
						new Date().getMonth(),
						new Date().getDate() - new Date().getDay()
					).getDate()
				),
				'{y}-{m}-{d}'
			)
			searchFormState.value.createTime = dateArray
			break
		case '4':
			var dateArray = []
			dateArray[0] = tool.parseTime(new Date(new Date().getFullYear(), new Date().getMonth(), 1), '{y}-{m}-{d}')
			dateArray[1] = tool.parseTime(
				new Date(new Date().getFullYear(), new Date().getMonth() + 1, 1) - 1,
				'{y}-{m}-{d}'
			)
			searchFormState.value.createTime = dateArray
			break
		case '5':
			var dateArray = []
			dateArray[0] = tool.parseTime(new Date(new Date().getFullYear(), new Date().getMonth() - 1, 1), '{y}-{m}-{d}')
			dateArray[1] = tool.parseTime(new Date(new Date().getFullYear(), new Date().getMonth(), 1) - 1, '{y}-{m}-{d}')
			searchFormState.value.createTime = dateArray
			break
		default:
			var dateArray = []
			dateArray[0] = tool.parseTime(new Date(), '{y}-{m}-{d}')
			dateArray[1] = tool.parseTime(new Date(), '{y}-{m}-{d}')
			searchFormState.value.createTime = dateArray
			break
	}
}
</script>
